<script setup lang="ts">
import {ref, computed,inject,nextTick} from 'vue'
import {Message} from "@arco-design/web-vue";
import {saveAs} from 'file-saver';
import jsonBig from "json-bigint";
import Print from "@/utils/print";
import { send } from 'vite';
const props = defineProps({
  visible: Boolean,
  crudRef: {
    required: true
  },
  dataList: {
    required: true
  },
  selected: {
    type: Array,
    default: () => []
  },
})

const tableList = inject('tableList');
const infoGet = inject('infoGet',null);
const config = ref({
  title: '',
  data: [],
  api: Function,
  addType:undefined, //1列表 //2添加编辑
  displayDataIndex: '',
  form: {},
  ApiType: undefined,
  isDownload: undefined,
  isPrint: undefined,
  cancel: ()=>{},
})
const form = ref({})
const loading = ref({
  value: false,
  count: 0,
})
const visible = ref()
const records = ref([])
const maFormRef = ref()
const emit = defineEmits(['cancel'])
const options = computed(() => {
  let defaultOptions = {
    showButtons: false
  }
  return {...defaultOptions, ...config.value.form.options}
})
const multipleAction = async () => {
  if(loading.value.value){
    Message.warning('数据正在执行中请稍后再试!')
    return false
  }
  if (loading.value.count > 0) {
    cancel()
    return;
  }
  if (maFormRef.value && await maFormRef.value.validateForm()) {
    return false
  }

  function readTextFromFile(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onload = function (event) {
        resolve(event.target.result);
      };

      reader.onerror = function (error) {
        reject(error);
      };

      reader.readAsText(file, 'utf-8');
    });
  }

  const key = config.value.form?.key || 'ids';
  if (config.value.isDownload) {
    let response = await config.value.api(Object.assign({[key]: props.selected}, form.value))
    let contentType = response.headers['content-type'].toLowerCase()?.split(';')[0];
    if (contentType.includes('json')) {
      let responseText = await readTextFromFile(response.data)
      response.data = JSON.parse(JSON.stringify(jsonBig({storeAsString: true}).parse(responseText)));
      if (response.data.success === false) {
        Message.error(response.data.message)
        return
      }
    }
    let disposition = response.headers['content-disposition']?.split(';')[2]?.split('=')[1]?.split('\'')[2]
    saveAs(new Blob([response.data], {type: contentType}), decodeURIComponent(disposition))
  } else {
    loading.value.value = true
    console.log(records)
    for (let i = 0; i < records.value.length; i++) {
      let item = records.value[i]
      item.loading = true
      try {
        let response
        if (config.value.ApiType) {
          response = await config.value.api(config.value.ApiType, Object.assign({[key]: [item[config.value.form?.id || 'id']]}, form.value))
        } else {
          response = await config.value.api(Object.assign({[key]: [item[config.value.form?.id || 'id']]}, form.value))
        }
        item.success = response.success === true
        item.result = response.message || (response.success === true ? `成功！` : `失败！`)
      } catch (e) {
        item.success = false
        item.result = e.message || `失败！`
      } finally {
        loading.value.count++
        item.loading = false
      }
    }
    if(config.value.addType==2){
      infoGet()
    }else{
      if(props.dataList[0]?.count){
        tableList('tray_list')
      }else{
        tableList()
      }
    }
    
    // props.crudRef.refresh()
  }
  loading.value.value = false
  // 增加submited事件
  if (typeof config.value.form?.submited == 'function') {
    config.value.form.submited(records.value)
  }
}
/*
* @param button
* @param button.title 窗口标题
* @param button.api   接口地址
* @param button.form  表单配置
* @param button.action  自定义方法,优先级高于api
* @param button.displayDataIndex  展示编号的字段,默认 shipment_no > number > name
* */
const open = async (button) => {
  if (!props.selected || props.selected.length == 0) {
    Message.error('至少选择一条数据')
    return;
  }
  if(button?.carType && props.selected.length>1){
    Message.error('只能选择一条数据')
    return;
  }
  if (button.action && typeof button.action === 'function') {
    button.action(props.selected)
    return;
  }
  if (!button.api || ('function' !== typeof button.api && 'function' !== typeof button.api.value)) {
    Message.error('缺少接口配置')
    return;
  }
  let api = typeof button.api === 'object' ? button.api.value : button.api
  config.value.title = 'object' === typeof button.title ? button.title.value : button.title
  config.value.displayDataIndex = button.displayDataIndex ? button.displayDataIndex : ''
  config.value.api = api
  config.value.form = button.form ? button.form : null
  config.value.ApiType = button.ApiType ? button.ApiType : null
  config.value.isDownload = button.isDownload ? button.isDownload : null
  config.value.isPrint = button.isPrint ? button.isPrint : null
  config.value.addType = button.addType ? button.addType : null

  config.value.cancel = button.cancel ? button.cancel : ()=>{}
  let keyIndex =  config.value.form?.id || 'id'
  if(button?.listSelected){
    keyIndex=button?.listSelected
  }
  records.value=JSON.parse(JSON.stringify(props.dataList.filter(i =>props.selected.includes(i[keyIndex]))))
  console.log('records.value',records.value)
  form.value = button.form?.form ? JSON.parse(JSON.stringify(button.form.form)) : {}
  loading.value = {
    value: false,
    count: 0,
  }

  if (config.value.isPrint) {
    const key = config.value.form?.key || 'ids';
    let response = await config.value.api(Object.assign({[key]: props.selected}, form.value))
    if(!response.success){
      console.log(response)
      Message.error(response.message)
      return;
    }
    content.value = response.data
  }
  visible.value = true
  console.log(form)
  nextTick(() => {
    if(recordsList.value?.clientHeight){
      let height = recordsList.value.clientHeight; // 获取元素高度
      recordsListHeight.value=height/records.value.length
    }
  })
}
const handleScroll=()=>{
}
const cancel = () => {
  form.value = {}
  config.value.form = {}
  visible.value = false
  console.log(config.value)
  config.value.cancel()
}
const cancelText = computed(() => loading.value.count > 0 ? '关闭' : '执行')
defineExpose({
  open,
})
const recordsList = ref(null);
const recordsMain = ref(null);
const recordsListHeight=ref(null)


const percent = computed(() => {
  if(records.value.length>10 && loading.value.count>10){
     recordsMain.value.scrollTop =recordsListHeight.value*(loading.value.count-7)
  }
  let topercent=loading.value.count / records.value.length
  return topercent.toFixed(2);
})
const printType = ref('label')
const printTypeList = [
  {label: '标签纸', value: 'label'},
  {label: 'A4纸', value: 'a4'},
]
//初始化
const tableListRed=()=>{
  maFormRef.value.init()
}
const content = ref([])
const A4PrintList = computed(()=>{
  const result = [];
  for (let i = 0; i < content.value.length; i += 2) {
    const pair = [
          content.value[i],
          content.value[i + 1] || '', // 添加空对象防止数组越界
        ]
    result.push(pair);
  }
  return result;
})
const printRef = ref()
const printLabel = () => {
  new Print(printRef.value,{noStyle:true,style:'@page{size:'+ (printType.value =='a4' ? 'A4' : '100mm 100mm') +';margin:0;}'})
}
</script>

<template>
  <a-modal :title="config.title" :visible='visible' @cancel="cancel" @ok="multipleAction" width="50%"
           :bodyStyle="{'height':'70vh'}"
           unmount-on-close
           :hide-cancel="loading.count > 0"
           :closable="!loading.value"
           :escToClose="!loading.value"
           :ok-text="cancelText">
    <template #footer v-if="config.isPrint">
      <a-space>
        <a-radio-group v-model="printType" :options="printTypeList"/>
        <a-button @click="printLabel" type="primary">打印</a-button>
      </a-space>
    </template>
    <p v-if="!config.form && !config.isPrint">确认{{ config.title }}吗?</p>
    <ma-form v-if="config.form" v-bind="config.form" v-model="form" :options="options" ref="maFormRef"></ma-form>
    <div v-if="config.isPrint" ref="printRef">
      <div v-if="printType !=='a4'" v-for="item in content" v-html="item" class="print-break"
           style="margin-bottom: 2mm;
           display: flex;
           justify-content: center;
           align-items: center;
           overflow: hidden;
           page-break-after:always;
           break-after: page;
           box-sizing: border-box;"></div>
      <template v-else >
        <div style="display: flex; flex-flow: row; width: 100%;" v-for="(item,i) in A4PrintList" :style="{'break-after': (i+1)%3===0 ? 'page' : 'inherit'}">
          <div style="width: 50%; display: flex; justify-content: center;" v-for="pair in item" v-html="pair"></div>
        </div>
      </template>
    </div>
    <!-- todo 成功批量反馈增加结果下载    -->
    <div v-if="!config.isDownload && !config.isPrint">
      <a-progress :percent="percent" v-if="loading.count"></a-progress>
      <div ref="recordsMain" class="h-96 overflow-y-auto"   @scroll="handleScroll">
        <div ref="recordsList">
            <a-row justify="start" v-for="(item,i) in records"
                class="border align-center justify-center text-center items-center"
                :class="{
          'bg-gray-300':item.loading,
          'bg-green-300':item.success,
          'bg-red-300':!item.success && item.result
              }">
            <a-col :span="2" class="bg-gray-300 h-8 leading-8">{{ i + 1 }}</a-col>
            <a-col :span="14" class="h-8 leading-8">
              {{ item[config.displayDataIndex] || item.shipment_no || item.number || item.name || item.id }}
            </a-col>
            <a-col :span="8" class="h-8 leading-8 overflow-hidden">
              <a-spin v-if="item.loading"></a-spin>
              <div v-else class="overflow-hidden">{{ item.result }}</div>
            </a-col>
          </a-row>
        </div>
      </div>
      
      
    </div>
  </a-modal>
</template>

<style scoped>
@media print {
  .print-break{
    break-after: page;
  }
}
</style>